<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :canFullscreen="false" :title="title" @ok="handleSubmit" :width="width"  destroyOnClose>
    <Row v-if="orderGoodsList.length > 1" :gutter="[24, 24]">
      <Col :span="14">
        <RefundGoodsList :orderGoodsList="orderGoodsList" @select="handleSelectOrderGoods"/>
      </Col>
      <Col :span="10">
        <BasicForm @register="registerForm" />
      </Col>
    </Row>
    <BasicForm v-else @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, nextTick } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { RefundFormSchema } from "./data"
  import { Tag, Row, Col, Tooltip } from "ant-design-vue"
  import { useMessage } from "/@/hooks/web/useMessage"
  import RefundGoodsList from "./RefundGoodsList.vue"
  const { createMessage } = useMessage()
  const emit = defineEmits(["register", "success"])
  const record = ref<any>({})
  const refundApi = ref<Function>()
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: RefundFormSchema,
    labelWidth: 100,
    showActionButtonGroup: false,
  })
  const selectOrderGoodsList = ref<any[]>()

  const orderGoodsList = ref<any[]>([])
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields()
    setModalProps({ confirmLoading: false })
    console.log("data.record: ", data.record)
    orderGoodsList.value = data.record.detailList || []
    selectOrderGoodsList.value = orderGoodsList.value.length == 1 ? orderGoodsList.value : []
    refundApi.value = data.refundApi
    record.value = { ...data.record }
    nextTick(() => setFieldsValue({
       orderGoodsInfo: getSelectOrderGoodsInfo(),
       ...record.value
    }))
  })
  const title = computed(() => "退款")
  const width = computed(() => orderGoodsList.value.length > 1 ? '1000px' : '500px')
  const getSelectOrderGoodsInfo = () => {
    if (!selectOrderGoodsList.value || selectOrderGoodsList.value.length == 0) {
      return '全部商品'
    }
    return selectOrderGoodsList.value?.map(e => {
      return `${e.goodsName}（${e.id}）`
    }).join('\n')
  }
  async function handleSubmit(v) {
    selectOrderGoodsList.value = selectOrderGoodsList.value || []
    try {
      let values = await validate()
      // 校验退款金额
      if (values.refundPrice <= 0) {
        createMessage.error("退款金额必须大于0")
        return
      }

      const goodsCanRefundPriceList = selectOrderGoodsList.value.map(e => e.totalPayPrice - e.refundRealPrice)
      const canRefundPrice = goodsCanRefundPriceList.length > 0 ? goodsCanRefundPriceList.reduce((prev, item) => {
        return (prev || 0 ) + item
      }) : -1
      
      console.log('canRefundPrice', canRefundPrice)
      if (canRefundPrice != -1 &&  values.refundPrice > canRefundPrice) {
        createMessage.error("退款金额大于商品可退款金额")
        return
      }

      setModalProps({ confirmLoading: true })
      refundApi.value && await refundApi.value({
        orderNo: record.value.orderNo,
        refundReason: values.refundReason,
        refundPrice: values.refundPrice,
        goodsOrderId: selectOrderGoodsList.value.length > 0 ? selectOrderGoodsList.value[0].id : null
      })
      closeModal()
      emit("success")
      createMessage.success(`${unref(title)}成功`)
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }

  const handleSelectOrderGoods = (orderGoods) => {
    selectOrderGoodsList.value = [orderGoods]
    setFieldsValue({
      orderGoodsInfo: getSelectOrderGoodsInfo()
    })
  }
</script>
